// preload.js
const { contextBridge, ipcRenderer } = require('electron');

// 将安全的API暴露给渲染进程
contextBridge.exposeInMainWorld('electronAPI', {
    // 可以在这里添加需要暴露的API
    // 例如：
    // send: (channel, data) => ipcRenderer.send(channel, data),
    // receive: (channel, func) => ipcRenderer.on(channel, (event, ...args) => func(...args))
    
    // 获取应用版本信息
    getAppVersion: () => {
        return process.env.npm_package_version || '1.0.0';
    },
    
    // 检查是否是开发环境
    isDevelopment: () => {
        return process.env.NODE_ENV === 'development';
    }
});

// 允许渲染进程访问fetch API并自动处理跨域请求
Object.defineProperty(window, 'fetch', {
    configurable: true,
    enumerable: true,
    writable: true,
    value: async function(url, options = {}) {
        // 自动添加跨域头信息
        const headers = new Headers(options.headers || {});
        
        // 设置默认的Content-Type
        if (!headers.has('Content-Type')) {
            headers.set('Content-Type', 'application/json');
        }
        
        // 合并选项
        const fetchOptions = {
            ...options,
            headers,
            credentials: options.credentials || 'include' // 包含cookie等凭证
        };
        
        try {
            // 调用原生fetch
            return await fetch(url, fetchOptions);
        } catch (error) {
            console.error('Fetch error in Electron:', error);
            throw error;
        }
    }
});

// 确保WebSocket也能正常工作并处理跨域
Object.defineProperty(window, 'WebSocket', {
    configurable: true,
    enumerable: true,
    writable: true,
    value: function(url, protocols) {
        // 创建原始WebSocket实例
        const ws = new WebSocket(url, protocols);
        
        // 增强WebSocket实例，如果需要
        // ws.addEventListener('open', () => {
        //     console.log('WebSocket connection opened:', url);
        // });
        
        return ws;
    }
});